﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MySql.Data.MySqlClient;
using System.Data;
using System.Configuration;

namespace SindSaudeCamadas.Dados
{
    public class Login
    {
        Conex conexao = new Conex();
        public int login(string StrNome,string StrSenha)
        {
            MySqlCommand cmdSQL = new MySqlCommand();
            MySqlDataAdapter daSQL = new MySqlDataAdapter();
            MySqlDataReader dr = null;
            int idLogin = 0;

            cmdSQL.CommandType = CommandType.Text;
            cmdSQL.CommandText = "SELECT ID FROM tblogins WHERE STRNOME = @STRNOME AND STRSENHA = @STRSENHA;";

            string conex = ConfigurationManager.AppSettings["SindSaude"].ToString();
            cmdSQL.Connection = conexao.retornaConexao(conex);
            try
            {
                cmdSQL.Parameters.AddWithValue("@STRNOME", StrNome);
                cmdSQL.Parameters.AddWithValue("@STRSENHA", StrSenha);

                cmdSQL.Connection.Open();
                dr = cmdSQL.ExecuteReader();
                if (dr.Read())
                {
                    idLogin = Convert.ToInt32(dr[0]);
                }
            }
            catch (Exception)
            {
                
                throw;
            }
            finally
            {
                cmdSQL.Connection.Dispose();
                cmdSQL.Dispose();
                daSQL.Dispose();
            }            
            if (idLogin > 0)
            {
                try
                {
                    cmdSQL.CommandText = "update tblogins set dtUltimoAcesso = SYSDATE() where id = @ID";
                    cmdSQL.Parameters.AddWithValue("@ID", idLogin);

                    cmdSQL.Connection.Open();
                    cmdSQL.ExecuteNonQuery();
                }
                catch (Exception)
                {
                    throw;
                }
                finally
                {
                    cmdSQL.Connection.Dispose();
                    cmdSQL.Dispose();
                    daSQL.Dispose();
                }
            }
            return idLogin;
        }
    }
}
